#include "app_adc.h"
#include "iot_adc.h"
#include "app_led.h"
#include "iot_errno.h"
#include "app_log.h"

const static char *TAG = "app_adc.c";

#define ADC_GPIO 13
#define ADC_CHANNEL 6
#define ADC_VREF_VOL 1.8
#define ADC_COEFFICIENT 4
#define ADC_RATIO 4096
bool LED_STATE = false;

/**
 * @brief get ADC sampling value and convert it to voltage
 *
 */
int get_voltage(uint8_t adc_channel, float *volt)
{
    unsigned int ret;
    unsigned short data;

    ret = IoTAdcRead(adc_channel, &data, IOT_ADC_EQU_MODEL_8, IOT_ADC_CUR_BAIS_DEFAULT, 0xff);

    if (ret != IOT_SUCCESS)
    {
        MY_LOGI(TAG,"ADC Read Fail\n");
        return IOT_FAILURE;
    }
    else
    {
        *volt = (float)data * ADC_VREF_VOL * ADC_COEFFICIENT / ADC_RATIO;
        return IOT_SUCCESS;
    }
}

void gas_module_test_task(void)
{
    float vlt = 0;
    static int smoke = 0;
    /* 10秒后可燃气体传感器才能正常检测 */
    osDelay(1000);
    /* init LED IO*/
    led_init(5);
    while(1)
    {
        int ret = get_voltage(ADC_CHANNEL,&vlt);
        if (ret != IOT_SUCCESS)
        {
            MY_LOGI(TAG,"Mq7GatherVoltage failed");
            continue;
        }
        MY_LOGI(TAG,"vlotage is %.3f\r\n", vlt);
        if (vlt > 0.3)
        {
            /* 检测到可燃气体，如果之前没有报警，则点亮LED灯，如果之前已经点亮了，则不再点亮 */
            if(LED_STATE == false)
            {
                led_ctrl(5,1,50);
            }
            else
            {
                // no action
            }
            LED_STATE = true;
        }
        else 
        {
            /* 未检测到可燃气体，如果之前有报警，则熄灭LED灯，如果之前已经熄灭了，则不再熄灭 */
            if(LED_STATE == true)
            {
                led_ctrl(5,0,50);
            }
            else
            {
                //no action
            }
            LED_STATE = false;
        }
        //控制检测频率，目前暂定2秒一次
        osDelay(200);
    }
    return;
}


